//
//  SPBaseViewViewController.m
//  ShopProject
//
//  Created by kuangbiao on 2018/11/26.
//  Copyright © 2018 KB. All rights reserved.
//

#import "SPBaseViewViewController.h"

@interface SPBaseViewViewController ()<UIGestureRecognizerDelegate>

@end

@implementation SPBaseViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //set background color
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"fafafa"]];
    if ([self.view viewWithTag:1041] != nil){//tableview
        if ([[self.view viewWithTag:1041] isKindOfClass:[UITableView class]]){
            UITableView *tableView = [self.view viewWithTag:1041];
            [tableView setBackgroundColor:kViewBackgroundColor];
        }
    }
    
    //add gesture
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    //end edit
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self.view endEditing:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UIView *)createHeaderView{
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, WIDTH, 10);
    headerView.backgroundColor = kViewBackgroundColor;
    return headerView;
}


- (void)backAction {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - UITapGestureRecognizer
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIButton class]])
    {
        return NO;
    }
    return YES;
}

- (void)keyboardHide{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self.view endEditing:YES];
    
    if ([self.view viewWithTag:1041] != nil){//tableview
        if ([[self.view viewWithTag:1041] isKindOfClass:[UITableView class]]){
            UITableView *tableView = [self.view viewWithTag:1041];
            tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }
    }
}


#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self moveField:textField leaveView:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self moveField:textField leaveView:NO];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self keyboardHide];
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self keyboardHide];
}


- (void)moveField:(UITextField *)textField leaveView:(BOOL)leave{
    
    if (textField.frame.origin.y > self.view.frame.size.height - 252 - textField.frame.size.height) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            if ([self.view viewWithTag:1041] == nil){
                
                //view无scroll view情况下使用
                int movement = (leave ? - (textField.frame.origin.y - 88): textField.frame.origin.y - 88);
                self.view.frame = CGRectOffset(self.view.frame, 0, movement);
            }
        }];
    }
}



- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if ([self.view viewWithTag:1041] != nil){//tableview
        
        if ([[self.view viewWithTag:1041] isKindOfClass:[UITableView class]]){
            
            UITableView *tableView = [self.view viewWithTag:1041];
            UIView *view = textField.superview;
            while (![view isKindOfClass:[UITableViewCell class]]) {
                
                view = [view superview];
                
            }
            
            UITableViewCell *cell = (UITableViewCell *)view;
            tableView.contentInset = UIEdgeInsetsMake(0, 0, 252, 0);
            [tableView scrollToRowAtIndexPath:[tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            
        }
        
        
    }
    
    
    return YES;
    
}


//MARK:-
//MARK:- input_MAX
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    // return btn￼
    if ([string isEqualToString:@"\n"]){
        
        [[[UIApplication sharedApplication] keyWindow] endEditing:true];
        return false;
    }
    
    //cardNo - 分割带空格
    //unionpay code - 分割带空格
    //PS:一定要写在delete btn之前
    if (textField.tag == 60 || textField.tag == 61){
        NSRange tr = [self selectedRange:textField];
        
        NSString *new = [textField.text substringToIndex:tr.location];
        
        if ([string isEqualToString:@""] && [new hasSuffix:@" "]) {
            
            NSString *ns = [new substringToIndex:new.length - 1];
            NSString *es = [textField.text substringFromIndex:tr.location];
            
            textField.text = [ns stringByAppendingString:es];
            tr.location = tr.location - 1;
            [self setSelectedRange:textField :tr];
        }
        
    }
    
    
    //delete btn
    if (string.length == 0){
        return true;
    }
    
    
    //amount txt
    if (textField.tag == 55){
        // 非常烂的代码，然而它没有BUG，所以请不要去动它
        // dot
        if ([string isEqualToString:@"."] && [textField.text isEqualToString:@""]) {
            textField.text = @"0";
            return true;
        }
        
        NSArray *tmpAr = [textField.text componentsSeparatedByString:@"."];
        if (tmpAr.count > 1) {
            
            if ([string isEqualToString:@"."]) {
                return false;
                
            }else{
                
                if ([tmpAr[1] length] > 1) {
                    if ([string isEqualToString:@""]) {
                        return true;
                    }
                    return false;
                }
                return true;
            }
        }else{
            
            if ([textField.text isEqualToString:@"0"]){
                if ([string isEqualToString:@"0"]) {
                    return false;
                }else{
                    if ([string isEqualToString:@"."]) {
                        return true;
                    }else{
                        textField.text = @"";
                        return true;
                    }
                }
            }else{
                
                if ([string isEqualToString:@"."]) {
                    return true;
                }
                
                return (textField.text.length + 1 <= 6);
            }
        }
    }
    
    //id_card
    if (textField.tag == 54){
        
        
        NSString *tmpString = @"WXwx0123456789";
        NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:tmpString].invertedSet;
        
        NSString *filtered = [string componentsSeparatedByCharactersInSet:cs].firstObject;
        if (![filtered isEqualToString: string]){
            return false;
        }
        
        if (range.location < 18 && textField.text.length + 1 < 19 && ([string isEqualToString:@"w"] || [string isEqualToString:@"W"] || [string isEqualToString:@"x"])){
            //如果不超过，用户用九宫格输入wWx，则自动补入X，并不让wWx录入
            textField.text = [textField.text stringByAppendingString:@"X"];
            
            return false;
        }
        
    }
    
    
    int existedLength = (int)textField.text.length;
    int selectedLength = (int)range.length;
    int replaceLength = (int)string.length;
    
    if (existedLength - selectedLength + replaceLength > [self txtMaxLength:(int)textField.tag]) {
        return false;
    }
    
    
    return true;
    
}


- (void)textFieldDidChange:(UITextField *)textField{
    
    
    if (textField.text.length > [self txtMaxLength:(int)textField.tag]){
        
        textField.text = [textField.text substringToIndex:[self txtMaxLength:(int)textField.tag]];
        
    }
    
}

- (int)txtMaxLength:(int)type{
    
    
    int txtMaxLength = 0;
    
    switch (type){
        case 50://mobile
            txtMaxLength = 11;
            break;
        case 51://password
            txtMaxLength = 16;
            break;
        case 52://sms code
            txtMaxLength = 6;
            break;
        case 53://name
            txtMaxLength = 99;
            break;
        case 54://idCard
            txtMaxLength = 18;
            break;
        case 55://amount
            txtMaxLength = 10;
            break;
        case 56://cardNo
            txtMaxLength = 25;
            break;
        case 57://cvv2
            txtMaxLength = 3;
            break;
        case 58://expDate
            txtMaxLength = 4;
            break;
        case 59://pay password
            txtMaxLength = 6;
            break;
        case 60://cardNo - 分割带空格
            txtMaxLength = 25 + 6;
            break;
        default:
            txtMaxLength = 99;
            break;
    }
    
    return txtMaxLength;
    
}

//MARK:- conversion amount [edit did end]
- (IBAction)conversionAmount:(UITextField *)sender{
    
    NSArray *tmpAr = [sender.text componentsSeparatedByString:@"."];
    
    if (tmpAr.count == 1) {
        
        sender.text = [sender.text stringByAppendingString:@".00"];
        
        if ([sender.text isEqualToString:@".00"]) {
            
            sender.text = @"0.00";
            
        }
        
    }else if (tmpAr.count == 2){
        
        NSString *tmpStr = tmpAr[0];
        
        if (tmpStr.length == 0){
            
            tmpStr = @"0";
        }else{
            
            tmpStr = sender.text;
        }
        
        NSString *tmpStr2 = tmpAr[1];
        
        if (tmpStr2.length == 1){
            
            sender.text = [tmpStr stringByAppendingString:@"0"];
            
        }else if (tmpStr2.length == 0){
            
            sender.text = [tmpStr stringByAppendingString:@"00"];
        }
        
    }
    
}

//MARK:- CardNo
#pragma mark -
- (IBAction)conversionCardNo:(UITextField *)sender {
    
    NSRange tr = [self selectedRange:sender];
    NSString *locS = [sender.text substringToIndex:tr.location];
    locS = [locS stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
    NSString *t = [sender.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *theString = @"";
    int block = (int)t.length / 4;
    
    for (int index = 0; index <= block; index++) {
        
        if (index == block) {
            theString = [theString stringByAppendingString:[t substringWithRange:NSMakeRange(index * 4, t.length % 4)]];
        }else{
            theString = [theString stringByAppendingString:[t substringWithRange:NSMakeRange(index * 4, 4)]];
            theString = [theString stringByAppendingString:@" "];
        }
        
    }
    sender.text = theString;
    tr.location = locS.length + locS.length / 4;
    
    [self setSelectedRange:sender :tr];
    
}


- (NSRange)selectedRange:(UITextField *)sender {
    UITextPosition* beginning = sender.beginningOfDocument;
    
    UITextRange *selectedRange = sender.selectedTextRange;
    UITextPosition *selectionStart = selectedRange.start;
    UITextPosition *selectionEnd = selectedRange.end;
    
    const NSInteger location = [sender offsetFromPosition:beginning toPosition:selectionStart];
    const NSInteger length = [sender offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

- (void)setSelectedRange:(UITextField *)sender :(NSRange)range  // 备注：UITextField必须为第一响应者才有效
{
    UITextPosition *beginning = sender.beginningOfDocument;
    
    UITextPosition *startPosition = [sender positionFromPosition:beginning offset:range.location];
    UITextPosition *endPosition = [sender positionFromPosition:beginning offset:range.location + range.length];
    UITextRange *selectionRange = [sender textRangeFromPosition:startPosition toPosition:endPosition];
    
    [sender setSelectedTextRange:selectionRange];
}

@end
